package com.yuyu.commons.config.feign;

import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jodd.util.StringUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author
 * @version 1.0
 * @description: TODO
 * @date 2022/10/10 9:50
 */
@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);//设置子线程共享
        if (Objects.nonNull(servletRequestAttributes)) {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String token = request.getHeader("F-SHOP-LOGIN");
            if (StringUtil.isNotEmpty(token)) {
                requestTemplate.header("F-SHOP-LOGIN", token);
            }
        }
    }

    /**
     * 打印基本日志
     * @return
     */
    @Bean
    public Logger.Level level() {
        return Logger.Level.BASIC;
    }
}
